<?php
namespace app\admin\controller;

use think\facade\Db;

class Dashboard extends \app\BaseController
{
    /**
     * 仪表板首页
     */
    public function index()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        // 获取统计数据
        $statistics = $this->getStatistics();
        
        // 获取今日数据
        $todayData = $this->getTodayData();
        
        // 获取最新的商户申请
        $recentMerchants = $this->getRecentMerchants();
        
        // 获取管理员信息
        $adminUser = $_SESSION['admin_user'];
        
        // 准备视图数据
        $data = [
            'title' => '仪表板',
            'current_menu' => 'dashboard',
            'statistics' => $statistics,
            'today_data' => $todayData,
            'recent_merchants' => $recentMerchants,
            'admin_user' => $adminUser
        ];
        
        // 使用视图渲染页面
        return view('dashboard/index', $data);
    }
    
    /**
     * 获取统计数据
     */
    private function getStatistics()
    {
        try {
            return [
                'user_count' => 0, // 暂时设为0，因为没有用户表
                'merchant_count' => Db::name('merchant')->count(),
                'pending_count' => Db::name('merchant')->where('status', 2)->count(), // 已提交
                'approved_count' => Db::name('merchant')->where('status', 0)->count(), // 成功
                'rejected_count' => Db::name('merchant')->where('status', 4)->count(), // 已驳回
            ];
        } catch (\Exception $e) {
            return [
                'user_count' => 0,
                'merchant_count' => 0,
                'pending_count' => 0,
                'approved_count' => 0,
                'rejected_count' => 0,
            ];
        }
    }
    
    /**
     * 获取今日数据
     */
    private function getTodayData()
    {
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        
        try {
            return [
                'new_users' => 0, // 暂时设为0
                'new_merchants' => Db::name('merchant')
                                    ->where('create_time', '>=', $todayStart)
                                    ->where('create_time', '<=', $todayEnd)
                                    ->count(),
                'pending_today' => Db::name('merchant')
                                    ->where('status', 2)
                                    ->where('create_time', '>=', $todayStart)
                                    ->where('create_time', '<=', $todayEnd)
                                    ->count(),
            ];
        } catch (\Exception $e) {
            return [
                'new_users' => 0,
                'new_merchants' => 0,
                'pending_today' => 0,
            ];
        }
    }
    
    /**
     * 获取最近商户
     */
    private function getRecentMerchants()
    {
        try {
            return Db::name('merchant')
                    ->field('id,merchant_name,store_name,legal_person,mobile,status,create_time')
                    ->order('create_time', 'desc')
                    ->limit(10)
                    ->select()
                    ->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }
    
    /**
     * 获取图表数据
     */
    private function getChartData()
    {
        $dates = [];
        $merchantCounts = [];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $dateStart = strtotime($date . ' 00:00:00');
            $dateEnd = strtotime($date . ' 23:59:59');
            
            $dates[] = date('m-d', strtotime($date));
            
            try {
                $merchantCounts[] = Db::name('merchant')
                                     ->where('create_time', '>=', $dateStart)
                                     ->where('create_time', '<=', $dateEnd)
                                     ->count();
            } catch (\Exception $e) {
                $merchantCounts[] = 0;
            }
        }
        
        return [
            'dates' => $dates,
            'merchantCounts' => $merchantCounts
        ];
    }
    
    /**
     * 获取统计数据API
     */
    public function getStatisticsApi()
    {
        $type = $this->request->param('type', 'week');
        
        switch ($type) {
            case 'today':
                $data = $this->getTodayStatistics();
                break;
            case 'week':
                $data = $this->getWeekStatistics();
                break;
            case 'month':
                $data = $this->getMonthStatistics();
                break;
            default:
                $data = $this->getWeekStatistics();
        }
        
        return json(['code' => 1, 'data' => $data]);
    }
    
    /**
     * 今日统计
     */
    private function getTodayStatistics()
    {
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        
        try {
            return [
                'new_merchants' => Db::name('merchant')
                                    ->where('create_time', '>=', $todayStart)
                                    ->where('create_time', '<=', $todayEnd)
                                    ->count(),
                'approved_today' => Db::name('merchant')
                                     ->where('status', 0)
                                     ->where('update_time', '>=', $todayStart)
                                     ->where('update_time', '<=', $todayEnd)
                                     ->count(),
            ];
        } catch (\Exception $e) {
            return [
                'new_merchants' => 0,
                'approved_today' => 0,
            ];
        }
    }
    
    /**
     * 本周统计
     */
    private function getWeekStatistics()
    {
        $weekStart = strtotime('this week Monday 00:00:00');
        $weekEnd = strtotime('this week Sunday 23:59:59');
        
        try {
            return [
                'new_merchants' => Db::name('merchant')
                                    ->where('create_time', '>=', $weekStart)
                                    ->where('create_time', '<=', $weekEnd)
                                    ->count(),
                'approved_week' => Db::name('merchant')
                                    ->where('status', 0)
                                    ->where('update_time', '>=', $weekStart)
                                    ->where('update_time', '<=', $weekEnd)
                                    ->count(),
            ];
        } catch (\Exception $e) {
            return [
                'new_merchants' => 0,
                'approved_week' => 0,
            ];
        }
    }
    
    /**
     * 本月统计
     */
    private function getMonthStatistics()
    {
        $monthStart = strtotime(date('Y-m-01 00:00:00'));
        $monthEnd = strtotime(date('Y-m-t 23:59:59'));
        
        try {
            return [
                'new_merchants' => Db::name('merchant')
                                    ->where('create_time', '>=', $monthStart)
                                    ->where('create_time', '<=', $monthEnd)
                                    ->count(),
                'approved_month' => Db::name('merchant')
                                     ->where('status', 0)
                                     ->where('update_time', '>=', $monthStart)
                                     ->where('update_time', '<=', $monthEnd)
                                     ->count(),
            ];
        } catch (\Exception $e) {
            return [
                'new_merchants' => 0,
                'approved_month' => 0,
            ];
        }
    }
}
